﻿using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Navigation;
using WebUi.ServiceReference;

namespace WebUi.Views
{
	public partial class Home
	{
		readonly ManualResetEvent _ev = new ManualResetEvent(true);


		public Home()
		{
			InitializeComponent();
		}

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			ThreadPool.QueueUserWorkItem(state =>
									//Dispatcher.BeginInvoke(() =>
									{
										var c = new DataForClientsClient();
										LoadData(context: c);
										LoadCities(5000, c);
										c.CloseAsync();
									});
		}


		void _butRefreshData_Click(object sender, RoutedEventArgs e)
		{
			LoadData((String)_citiesCombo.SelectedValue);
		}


		void LoadData(String filter = null, Int32 timeout = 0, DataForClientsClient context = null)
		{
			var isClear = _ev.WaitOne(timeout);
			if (!isClear)
				return;

			var localContext = false;
			if (context == null)
			{
				context = new DataForClientsClient();
				localContext = true;
			}

			context.LastEntriesCompleted += (s, ea) =>
										{
											try
											{
												if (ea.Error != null || ea.Cancelled) return;

												//var z = TimeZoneInfo.Local.BaseUtcOffset;
												//var КОСТЫЛЬ = TimeSpan.FromTicks(1);
												//foreach (var entry in ea.Result)
												//{
												//// TODO: это должно делаться форматами в гриде так то..
												//var newTime = entry.TimeUtc.ToLocalTime() + КОСТЫЛЬ;
												// а то не присваивается из за успешной проверки на эквивалентность
												//entry.TimeUtc = newTime;
												//}
												var checkAccess = Dispatcher.CheckAccess();
												Action method = () => dataGrid.ItemsSource = ea.Result;
												if (!checkAccess)
													Dispatcher.BeginInvoke(method);
												else method();

											} finally
											{
												_ev.Set();
												if (localContext)
													context.CloseAsync();
											}
										};

			_ev.Reset();
			context.LastEntriesAsync(filter);
		}



		void LoadCities(Int32 timeout = 0, DataForClientsClient context = null)
		{
			var isClear = _ev.WaitOne(timeout);
			if (!isClear)
				return;

			var localContext = false;
			if (context == null)
			{
				context = new DataForClientsClient();
				localContext = true;
			}

			context.GetCitiesCompleted += (s, ea) =>
			{
				try
				{
					if (ea.Error != null || ea.Cancelled) return;

					ea.Result.Insert(0, "");


					var checkAccess = Dispatcher.CheckAccess();
					Action method = () => _citiesCombo.ItemsSource = ea.Result;
					if (!checkAccess)
						Dispatcher.BeginInvoke(method);
					else method();

				} finally
				{
					_ev.Set();
					if (localContext)
						context.CloseAsync();
				}
			};

			_ev.Reset();
			context.GetCitiesAsync();
		}


		void dataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
		{
			switch (e.PropertyName)
			{
				case "TimeUtc":
					e.Cancel = true;
					e.Column.DisplayIndex = 0;
					break;
				case "CityName":
					if (!String.IsNullOrEmpty((String)_citiesCombo.SelectedValue))
						e.Cancel = true;
					break;
			}
		}
	}
}